﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using KLS.PPDS.ApplicationService.Manager;
using log4net;
using LogManager = log4net.LogManager;
using System.Threading;
using System.Globalization;
using System.Web.Security;

namespace KLS.PPDS.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    /// <summary>
    /// MvcApplication
    /// </summary>
    public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));
        /// <summary>
        /// RegisterRoutes
        /// </summary>
        /// <param name="routes"></param>
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            
            //routes.MapRoute("Default", "{controller}.aspx/{action}/{id}",
            //new { controller = "Home", action = "Index", id = "" });

        }

        /// <summary>
        /// Application_Start
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            log4net.Config.DOMConfigurator.Configure();
            RegisterRoutes(RouteTable.Routes);
          // SetCulture("da-DK");
            log.Info(String.Format("App started at {0}", DateTime.Now));
        }
      
       
        /// <summary>
        /// Application_Error
        /// </summary>
        void Application_Error()
        {
            
             Exception exception = HttpContext.Current.Server.GetLastError();
             log.Error(exception);
             log.Error("exception from application error");
             //this.Server.ClearError();
             //this.Server.Transfer("~/error/UploadTooLarge.aspx");
          //   Response.Redirect("www.google.com");
        }

        /// <summary>
        /// Application_EndRequest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            DatabaseManager.CloseSession();
        }

        /// <summary>
        /// Session_Start
        /// </summary>
        protected void Session_Start()
        {
            Session["SessionStart"] = "1";
            //return RedirectToRouteResult("Account/LogIn");
            //return RedirectToRouteResult("Account/LogIn");

        }

        /// <summary>
        /// Session_End
        /// </summary>
        protected void Session_End()
        {
            Session["SessionStart"] = null;
            //return RedirectToRouteResult("Account/LogIn");
            //return RedirectToRouteResult("Account/LogIn");
            
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            ///* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
            try
            {
                var session_param_name = "ASPSESSID";
                var session_cookie_name = "ASP.NET_SessionId";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception ex)
            {
                //log.Error(ex);
                //var context = HttpContext.Current;
                //var errorInfo =
                //   "<br>Offending URL: " + context.Request.Url +
                //   "<br>Source: " + ex.Source +
                //   "<br>Message: " + ex.Message +
                //   "<br>Stack trace: " + ex.StackTrace;

                //context.Response.Write(errorInfo);
                //Server.ClearError();

                //var error = ex;
                //Server.ClearError();
                //Response.ContentType = "text/plain";
                //Response.Write(error ?? (object)"unknown");
                //Response.End();

            }

            try
            {
                string auth_param_name = "AUTHID";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch
            {
            }
        }

        private void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (null == cookie)
            {
                cookie = new HttpCookie(cookie_name);
            }
            cookie.Value = cookie_value;
            HttpContext.Current.Request.Cookies.Set(cookie);
        }
    }
}